package com.hmall.search.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.hmall.api.clients.ItemClient;
import com.hmall.api.dto.ItemDTO;
import com.hmall.common.utils.BeanUtils;
import com.hmall.search.domain.po.ItemDoc;
import com.hmall.search.service.ISearchService;
import org.apache.http.HttpHost;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class SearchServiceImpl implements ISearchService {
      private RestHighLevelClient restHighLevelClient;
      @Autowired
      private ItemClient itemClient;
      public SearchServiceImpl() {
          restHighLevelClient= new RestHighLevelClient(RestClient.builder(HttpHost.create("http://192.168.12.168:9200")));
      }
    @Override
    public void saveItem(Long id) {
        ItemDTO itemDTO = itemClient.queryItemById(id);
        if(itemDTO == null){
            return;
        }
        IndexRequest itemRequest = new IndexRequest("item").id(id.toString());
        ItemDoc itemDoc =BeanUtils.copyBean(itemDTO, ItemDoc.class);
        String jsonStr = JSONUtil.toJsonStr(itemDoc);
        itemRequest.source(jsonStr, XContentType.JSON);
        try {
            restHighLevelClient.index(itemRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
      }

    @Override
    public void deleteItem(Long id) {
          DeleteRequest deleteRequest = new DeleteRequest("item").id(id.toString());
          try {
              restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
          } catch (IOException e) {
              e.printStackTrace();
          }

    }
}
